﻿using UnityEngine;
using System.Collections;

//ÓÃÓÚÕœ¶·NPCµÄŸàÀëŒì²âºÍ×Ô¶¯Õœ¶·¿ÉÀ©Õ¹//
public class SceneFightNpc : MonoBehaviour
{
	public int MonsterId{
		get{
			return monsterId;
		}set{
			monsterId = value;
		}
	}
	
	Transform mainRoleTrans;
	Transform trans;
	PlayerAction playAct;
	private float autoCheckDis = 0.8f;
	private float autoFightDis = 0.2f;
	private float arrowShowDis = 1.0f;
	public GameObject arrowGuide;
	GameObject mainRole;
	int monsterId;
	float originalSpeed;
	
	//暂用//
	bool hasSend = false;
	
	// Use this for initialization
	void Start ()
	{
		if (!mainRole)
			mainRole = PlayerData.Instance ().MainRoleInstance;
		
		playAct = GetComponent<PlayerAction> ();
		
		originalSpeed = playAct.speed;
		
		mainRoleTrans = mainRole.transform;
		trans = transform;
		
		if (arrowGuide == null) {
			arrowGuide = GameObject.Find("Go");
		}
		
		if(arrowGuide == null){
			arrowGuide = (GameObject)Instantiate(Resources.Load(ResPath.GENERALFILE + "Go"));
		}
	}
	
	// Update is called once per frame
	void Update ()
	{
		
		if (Vector2Distance (mainRoleTrans.position, trans.position) >= arrowShowDis) {
			arrowGuide.SetActive (true);
		} else {
			arrowGuide.SetActive (false);
		}

		if (Vector2Distance (mainRoleTrans.position, trans.position) <= autoCheckDis) {
			playAct.StopWalkAround ();
			playAct.npcautoMove (mainRoleTrans.position);
			playAct.speed = 2.0f;
		} else {
			playAct.StartWalkAround ();
			playAct.speed = originalSpeed;
		}

		if (Vector2Distance (mainRoleTrans.position, trans.position) <= autoFightDis) {
			
			if(hasSend == true) return;
			
			EncounterToFight.GetInstance().SwitchToFightScene();
			
			ByteArrayEx byteArray = new ByteArrayEx();
			
			int sceneId = PlayerData.Instance().SceneId;
			byteArray.writeInt((int)SystemMsgFlag.NetMessageCS.NM_CS_BATTLE_PVE_BEGIN_SYN);
			byteArray.writeInt(sceneId);
			byteArray.writeInt(monsterId);
			
			MySocket.getInstance ().Async_Send (byteArray.byteArray);
			
			hasSend = true;
			
			//GameObject panelFight = GameObject.Find("Panel(NPC)");
			//panelFight.SendMessage("receiveFight",SendMessageOptions.DontRequireReceiver);
			
			Destroy(gameObject);//由服务器管理，暂时这样处理//
            Camera.mainCamera.GetComponent<ScenePlayerLogic>().removeNpc(gameObject.name);

		}
	}
	
	float Vector2Distance (Vector3 startPoint, Vector3 endPoint)
	{
		Vector2 position1 = new Vector2 (startPoint.x, startPoint.y);
		Vector2 position2 = new Vector2 (endPoint.x, endPoint.y);
		
		float distance = Vector2.Distance (position1, position2);
		return distance;
	}
}
